package com.cpr.ams.service.impl;

import com.cpr.ams.bean.BasePrivilege;
import com.cpr.ams.bean.BasePrivilegeExample;
import com.cpr.ams.exception.AmsException;
import com.cpr.ams.mapper.BasePrivilegeMapper;
import com.cpr.ams.mapper.extend.BasePrivilegeExtendMapper;
import com.cpr.ams.service.IBasePrivilegeService;
import com.cpr.ams.util.StatusCode;
import com.cpr.ams.vm.PrivilegeTree;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * @Description: 权限业务实现类
 * @Author: GX Cui
 * @Date 1:14 下午 2021/4/12
 * @Param
 * @Return
 */
@Service
public class BasePrivilegeServiceImpl implements IBasePrivilegeService {
    @Resource
    private BasePrivilegeMapper basePrivilegeMapper;
    @Resource
    private BasePrivilegeExtendMapper basePrivilegeExtendMapper;


    @Override
    public List<BasePrivilege> findAll() {
        return basePrivilegeMapper.selectByExample(new BasePrivilegeExample());
    }

    @Override
    public List<BasePrivilege> findByParentId(Integer parentId) {
        BasePrivilegeExample example = new BasePrivilegeExample();
        if(parentId == null){
            example.createCriteria().andParentIdIsNull();
        } else {
            example.createCriteria().andParentIdEqualTo(parentId);
        }
        return basePrivilegeMapper.selectByExample(example);
    }

    @Override
    public int saveOrUpdate(BasePrivilege privilege) throws AmsException {
        int i = -100;
        if(privilege.getId()!=null){
            basePrivilegeMapper.updateByPrimaryKey(privilege);
        } else {
            basePrivilegeMapper.insertSelective(privilege);
            i = privilege.getId();
        }
        return i;
    }

    @Override
    public List<PrivilegeTree> findPrivilegeTree() {
        return basePrivilegeExtendMapper.selectAll();
    }

    @Override
    public List<BasePrivilege> findByUserId(int id) {
        return basePrivilegeExtendMapper.selectByUserId(id);
    }

    @Override
    public List<BasePrivilege> findMenuByUserId(int id) {
        return basePrivilegeExtendMapper.selectMenuByUserId(id);
    }

    @Override
    public void deleteById(int id) throws AmsException {
        BasePrivilege role = basePrivilegeMapper.selectByPrimaryKey(id);
        if(role == null){
            throw new AmsException(StatusCode.PRIVILEGE_NOT_EXIST);
        }
        basePrivilegeMapper.deleteByPrimaryKey(id);
    }
}
